<?php
namespace app\api\controller;
use app\Response;
use QL\QueryList;
use \Curl\Curl;
use \Curl\MultiCurl;
use think\Db;

class Courseware {
	const HEADER = [
			        //填写从浏览器获取到的cookie
			        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 WangPai 2345Explorer/8.4.1.14998',
			    ];
            const OVERTIME = 3600;    //user_token 超时时间

            const CODE = array('200'=>'ok','202'=>'参数错误','253'=>'无效的userToken','254'=>'登录已失效,请重新登录','255'=>'账号在另一地点登录','404'=>'用戶不存在');       //状态码
			    
	public function get(){
		$chapter_id = isset($_GET['chapter_id'])?$_GET['chapter_id']:1;
		$page =  isset($_GET['page'])?$_GET['page']:1;
		$limit  = isset($_GET['limit'])?$_GET['limit']:50;
		$offset = ($page-1)*$limit;
		
		$sql = "SELECT c.*,a.name AS book_name,b.name AS chapter_name FROM `tbl_courseware` AS c LEFT JOIN `tbl_book` AS a ON c.book_id=a.book_id LEFT JOIN `tbl_chapter` AS b ON c.chapter_id=b.chapter_id LIMIT {$offset},{$limit}";
		$data = Db::connect("db_ppt")->query($sql);
		//$data = N::db('ppt')->query($sql);
		//$data = Db::connect("db_ppt")->name("tbl_courseware")->where('chapter_id',$chapter_id)->limit($offset,$limit)->select();

		$total = Db::connect("db_ppt")->name("tbl_courseware")->where('chapter_id',$chapter_id)->count();

		//$data = N::db('ppt')->queryAll('tbl_courseware', array('chapter_id = :chapter_id', array(':chapter_id' => $chapter_id)), array('limit' => $limit, 'skip' => $offset));
		//$total_sql = "SELECT count(*) AS total FROM `tbl_courseware` WHERE chapter_id=:chapter_id";
		//$total_info = N::db('ppt')->query($total_sql,array(':chapter_id'=>$chapter_id));
		//$total = isset($total_info['total'])?$total_info['total']:0;
		$allpage = !empty($limit)?(ceil($total/$limit)):1;
		$result = array('total'=>$total, 'allpage'=>$allpage, 'page'=>$page, 'limit'=>$limit, 'info'=>$data);
		Response::show(200,'ok',$result);
	}

	public function bookList(){
		$page =  isset($_GET['page'])?$_GET['page']:1;
		$limit  = isset($_GET['limit'])?$_GET['limit']:50;
		$offset = ($page-1)*$limit;
		$sql = "SELECT b.book_id,b.name,s.subject,g.grade,b.resource_num,b.download_progress,b.update_time FROM `tbl_book` AS b LEFT JOIN `ppt_subject` AS s ON b.subject_id=s.subject_id LEFT JOIN `ppt_grade` AS g ON b.grade_id=g.grade_id LIMIT {$offset},{$limit}";
		//$data = Db::connect("db_ppt")->name("tbl_book")->limit(10)->select();
		$data = Db::connect("db_ppt")->query($sql);
		$total = Db::connect("db_ppt")->name("tbl_book")->count();

		//$data = N::db('ppt')->query($sql);
		//$total_sql = "SELECT count(*) AS total FROM `tbl_book`";
		//$total_info = N::db('ppt')->query($total_sql);
		//$total = isset($total_info['total'])?$total_info['total']:0;
		$allpage = !empty($limit)?(ceil($total/$limit)):1;
		$result = array('total'=>$total, 'allpage'=>$allpage, 'page'=>$page, 'limit'=>$limit,  'info'=>$data);
		Response::show(200,'ok',$result);
	}

	public function chapterList(){
		$book_id = isset($_GET['book_id'])?$_GET['book_id']:1;
		$page =  isset($_GET['page'])?$_GET['page']:1;
		$limit  = isset($_GET['limit'])?$_GET['limit']:50;
		$offset = ($page-1)*$limit;

		$data = Db::connect("db_ppt")->name("tbl_chapter")->where('book_id',$book_id)->limit($offset,$limit)->select();
		$total = Db::connect("db_ppt")->name("tbl_chapter")->where('book_id',$book_id)->count();

		//$data = N::db('ppt')->queryAll('tbl_chapter', array('book_id = :book_id', array(':book_id' => $book_id)), array('limit' => $limit, 'skip' => $offset));
		//$total_sql = "SELECT count(*) AS total FROM `tbl_chapter` WHERE book_id=:book_id";
		//$total_info = N::db('ppt')->query($total_sql,array(':book_id'=>$book_id));
		//$total = isset($total_info['total'])?$total_info['total']:0;

		$allpage = !empty($limit)?(ceil($total/$limit)):1;
		$result = array('total'=>$total, 'allpage'=>$allpage, 'page'=>$page, 'limit'=>$limit, 'info'=>$data);
		Response::show(200,'ok',$result);
	}

	public function downloadFile(){
		$courseware_id = isset($_GET['courseware_id'])?$_GET['courseware_id']:1;
		$courseware = Db::connect("db_ppt")->name("tbl_courseware")->where('courseware_id',$courseware_id)->find();
		//$courseware = N::db('ppt')->queryOne('tbl_courseware', array('courseware_id = :courseware_id', array(':courseware_id' => $courseware_id)));
		$ppt_url = isset($courseware['unzip_path'])?$courseware['unzip_path']:'';
		$ppt_name = isset($courseware['name'])?$courseware['name']:'';
		$link = isset($courseware['link'])?$courseware['link']:'';

		//替换\t , \n , \r 或全角空格等
		$ppt_name = preg_replace('/\s/', '', $ppt_name);
		//重命名,判断文件类型
        		$save_ppt_name_z = substr($ppt_url,-5);
		$save_ppt_name_z = strstr($save_ppt_name_z,'.');
		$ppt_retype = substr($save_ppt_name_z,1);
		if($ppt_retype == 'ppt'){
			$content_type = 'application/vnd.ms-powerpoint';
		}else if($ppt_retype == 'pptx'){
			$content_type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
		}else if($ppt_retype == 'doc'){
			$content_type = 'application/msword';
		}else if($ppt_retype == 'docx'){
			$content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
		}else if($ppt_retype == 'swf'){
			$content_type = 'application/x-shockwave-flash';
		}else if($ppt_retype == 'pdf'){
			$content_type = 'application/pdf';
		}else{
			$content_type = 'application/octet-stream';
		}
		$filename = '../'.$ppt_url;
		$out_filename = $ppt_name;
		
	          	if(file_exists($filename) && $ppt_url){
	          		header("Content-type:application/octet-stream");
	          		header("Accept-Ranges:bytes");
	          		header("Content-Type:".$content_type);
	          		header("Content-Disposition:inline;filename=".$out_filename);
	          		header("Accept-Length:".filesize($filename));

	              	if(is_file($filename) && is_readable($filename)){
	                		$file = fopen($filename, "r");
	                		echo fread($file, filesize($filename));
	                		fclose($file);
	              	}
	          	}else{
	            	//echo 'error:'.$filename;
	            	//当文件不存在时，请求原链接下载文件
	            	Header("Location:$link"); 
	          	}
	}
	/**
	 * [login 登录]
	 * @return [type] [description]
	 */
	public function login(){
		$login_name = isset($_POST['login'])?$_POST['login']:'';
		$password = isset($_POST['password'])?$_POST['password']:'';
		$code = self::CODE;
		if($login_name && $password){
			$user_info = Db::connect("db_ppt")->name("tbl_user")->where('login_name',$login_name)->find();
			if($user_info){
				$userid = isset($user_info['userid'])?$user_info['userid']:0;
				$user_token = self::encryption($userid);
				$update = Db::connect("db_ppt")->name("tbl_user")->where('userid',$userid)->update(['user_token' => $user_token, 'last_login'=>date('Y-m-d H:i:s')]);
				$msg = isset($code[200])?$code[200]:'';
				$result = array('user_token'=>$user_token);
				return Response::show(200,$msg,$result);
			}else{				
				$msg = isset($code[404])?$code[404]:'';
				return Response::show(404,$msg);
			}
		}else{
			$msg = isset($code[202])?$code[202]:'';
			return Response::show(202,$msg);
		}
	}
	/**
	 * [updateToken 修改token,保证token的有效性]
	 * @param  [type] $userid [description]
	 * @return [type]         [description]
	 */
	 public static function updateToken($userid){
	 	$user_token = '';
	    	if($userid){
	    		$user_token = self::encryption($userid);
			$update = Db::connect("db_ppt")->name("tbl_user")->where('userid',$userid)->update(['user_token' => $user_token]);
	    	}
	    	return $user_token;
	    }
	 /**
	  * [check 校验token的有效性]
	  * @return [type] [description]
	  */
	 public function check(){
	 	$userToken = isset($_POST['userToken'])?$_POST['userToken']:'';
	 	$status = $this->checkToken($userToken);
	 	$code = self::CODE;
	 	$msg = isset($code[$status])?$code[$status]:'';
	 	Response::show($status,$msg);
	 }   
	 /**
	     * [checkToken 验证单点登录]
	     * @param  [int] $userid    [用户ID]
	     * @param  [string] $userToken [当前用户所使用的token]
	     * @return [type]            [description]
	     * 
	     */
	    public function checkToken($userToken){
	    	if($userToken){
	    		$info = self::decrypt($userToken);
	    		$userid = isset($info['userid'])?$info['userid']:'';
	    		$time = isset($info['time'])?$info['time']:'';

	    		$overtime = !empty(self::OVERTIME)?self::OVERTIME:60;
	    		//超时判断
	    		if(($time+$overtime)< time()){
	    			return 254;    //'登录已失效,请重新登录'
	    		}

	    		if($userid){
	    			//$user_info = N::db('ppt')->queryOne('tbl_user', array('userid = :userid', array(':userid' => $userid)));
	    			$user_info = Db::connect("db_ppt")->name("tbl_user")->where('userid',$userid)->find();
	    			if($user_info){
	    				$user_token = isset($user_info['user_token'])?$user_info['user_token']:'';
		    			if($user_token != $userToken){
		    				return 255;  //'账号在另一地点登录'
		    			}else{
		    				return 200;    //'ok'
		    			}
	    			}else{
	    				return 404;    //'用戶不存在'
	    			}	    			
	    		}else{
	    			return 253;    //'无效的userToken'
	    		}
	    	}else{
	    		return 254;     //'登录已失效,请重新登录'
	    	}
	    }

	    /**
	     * [encryption 加密]
	     * @param  [int] $userid [用户ID]
	     * @return [string]         [加密后的字符串]
	     */
	    public static function encryption($userid){
	    	//数字加密
	    	$time = time();
	    	$encry_Str = $userid.$time;
	    	$encry_Arr = str_split($encry_Str);
	    	$encry1 = array('z','x','c','v','b','n','m','a','s','d');
	    	$encry2 = array('f','g','h','j','k','l','q','w','e','r');
	    	$encry3 = array('t','y','u','i','o','p','A','S','D','F'); 
	    	$encry4 = array('G','H','J','K','L','Q','W','E','R','T');
	    	$encry5 = array('Y','U','I','O','P','Z','X','C','V','B');

	    	$encry = array(1=>$encry1,2=>$encry2,3=>$encry3,4=>$encry4,5=>$encry5);

	    	$encry_time = '';
	    	foreach ($encry_Arr as $key => $val) {
	    		$rand = $encry[rand(1,5)];
	    		$encry_time .= $rand[$val];
	    	}
	    	return $encry_time;
	    }
	    /**
	     * [decrypt 解密]
	     * @param  [string] $userToken [用户token]
	     * @return [array]            [userid和time时间戳]
	     */
	    public static function decrypt($userToken){
	    	$length = strlen($userToken);
	    	$userid = '';
	    	$time = '';
	    	if($userToken && $length>10){
	    		$encry_userid = substr($userToken,0,($length-10));
	    		$encry_time = substr($userToken,-10,10);
	    		$decrypt = array('z'=>0,'x'=>1,'c'=>2,'v'=>3,'b'=>4,'n'=>5,'m'=>6,'a'=>7,'s'=>8,'d'=>9,'f'=>0,'g'=>1,'h'=>2,'j'=>3,'k'=>4,'l'=>5,'q'=>6,'w'=>7,'e'=>8,'r'=>9,'t'=>0,'y'=>1,'u'=>2,'i'=>3,'o'=>4,'p'=>5,'A'=>6,'S'=>7,'D'=>8,'F'=>9,'G'=>0,'H'=>1,'J'=>2,'K'=>3,'L'=>4,'Q'=>5,'W'=>6,'E'=>7,'R'=>8,'T'=>9,'Y'=>0,'U'=>1,'I'=>2,'O'=>3,'P'=>4,'Z'=>5,'X'=>6,'C'=>7,'V'=>8,'B'=>9);
	    		//userid解密
	    		if(strlen($encry_userid)>1){
	    			$userid_Arr = str_split($encry_userid);
	    		
		    		foreach ($userid_Arr as $k => $v) {
		    			$userid .= $decrypt[$v];
		    		}
	    		}else{
	    			$userid .= $decrypt[$encry_userid];
	    		}	

	    		$userid = (int)$userid;

	    		//时间戳解密
		    	$time_Arr = str_split($encry_time);
		    	
		    	foreach ($time_Arr as $key => $val) {
		    		$time .= $decrypt[$val];
		    	}
		    	$time = (int)$time;
	    	}   	
	    	return array('userid'=>$userid,'time'=>$time);
	    }
	
	/**
	 * [encoding 编码转化]
	 * @param  string $str           [要转化的字符]
	 * @param  string $encoding_to   [要转化的目的编码]
	 * @param  string $encoding_from [原编码]
	 * @return [type]                [description]
	 */
	public static function encoding($str='', $encoding_to="UTF-8", $encoding_from="GBK"){
		if($str){
			//已知原编码为encoding_from，转换为encoding_to
			$str = mb_convert_encoding($str, $encoding_to, $encoding_from);
		}
		return $str;
	}
}
